package cc.linker.steplink.crm.controller.h5;

import cc.linker.steplink.crm.commons.Constants;
import cc.linker.steplink.crm.commons.domain.WxUser;
import cc.linker.steplink.crm.commons.utils.StringUtil;
import cc.linker.steplink.crm.merchanth5.commons.RequestFilter;
import cc.linker.steplink.crm.merchanth5.dao.MallDao;
import cc.linker.steplink.crm.response.GlobalException;
import cc.linker.steplink.crm.service.IClassificationService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/h5/classification")
@Slf4j
public class H5ClassificationController {

    @Autowired
    private IClassificationService classificationService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RequestFilter requestFilter;
    @Autowired
    private MallDao mallDao;

    /**
     * 商品分组列表
     *
     * @param pageIndex        页码
     * @param pageSize         页大小
     * @param groupId          分组id -1全部 0/null默认
     * @param order            排序0-默认1-销量2-商品价格3-上架时间
     * @param sort             acs desc
     * @param classificationId 类目id
     * @param key              关键字
     * @param groupIsOrg       是否大b 1-是0-否
     * @param customerId       分组所属用户id(不传取request中信息)
     * @param goodsType        商品类型 3-内容，4-专栏
     * @param moduleType       分组类型(用于在全部分组和默认分组时区分) 3-商品4-知识付费
     */
    @PostMapping("/listGoods")
    public PageInfo listGoods(@RequestBody Map<String, Object> param, HttpServletRequest request) {
        WxUser wxUser =  requestFilter.getWxUser(request);
        String orgId = wxUser.getOrgId();
        param.put("orgId", orgId);
        String customerId;
        if (!StringUtils.isEmpty(param.get("customerId"))) {
            customerId = param.get("customerId").toString();
        } else {
            customerId = wxUser.getCustomerId();
        }
        param.put("customerId", customerId);

        PageInfo result = new PageInfo<>();
        String listGoodsStr = "";
        Boolean isExitData = false;
        if(StringUtils.isEmpty(param.get("moduleId"))){
             listGoodsStr = stringRedisTemplate.opsForValue().get("home:group_list_goods_" + StringUtil.getStringByMap(param));
            if(StringUtils.isEmpty(listGoodsStr)){
                result =  classificationService.listGoodsByGroupId(param);
            }else{
                result = JSONObject.parseObject(listGoodsStr,PageInfo.class);
                isExitData = true;
            }
        }else{
            Map<String,Object> moduleInfo = classificationService.getModuleInfo(param);
            if(null == moduleInfo){
                throw GlobalException.build("参数错误");
            }
            // 1是自定义 2是分组 (change 8-19)
            int showType = Integer.parseInt(moduleInfo.get("showType").toString());
            // 3 商品；4知识商品
            Integer moduleType = Integer.valueOf(moduleInfo.get("moduleType").toString());
            param.put("moduleType",moduleType);
            switch (showType){
                case 2 :
                    param.put("groupId",moduleInfo.get("goodsGroupId"));
                    listGoodsStr = stringRedisTemplate.opsForValue().get("home:group_list_goods_"+ StringUtil.getStringByMap(param));
                    if(StringUtils.isEmpty(listGoodsStr)){
                        result =  classificationService.listGoodsByGroupId(param);
                    }else{
                        result = JSONObject.parseObject(listGoodsStr,PageInfo.class);
                        isExitData = true;
                    }
                    break;
                case 1:
                    listGoodsStr = stringRedisTemplate.opsForValue().get("home:group_list_goods_"+ StringUtil.getStringByMap(param));
                    if(StringUtils.isEmpty(listGoodsStr)){
                        result =  classificationService.listGoodsCustom(param);
                    }else{
                        result = JSONObject.parseObject(listGoodsStr,PageInfo.class);
                        isExitData = true;
                    }
                    break;
                default:
                    throw GlobalException.build("参数错误");

            }
        }
        //REDIS没有缓存的情况下添加10秒缓存 缓解接口压力（大并发下）
        if(!isExitData) {
            stringRedisTemplate.opsForValue().set("home:group_list_goods_" + StringUtil.getStringByMap(param), JSON.toJSONString(result, SerializerFeature.WriteMapNullValue), 15, TimeUnit.SECONDS);
        }
        if(result.getList()!=null && result.getList().size()>0){
            List<Map> goodsList = result.getList();
            if(goodsList!=null && goodsList.size()>0){
                for(Map mallGoods: goodsList){
                    if(!StringUtils.isEmpty(mallGoods.get("isSeckill")) && "1".equals(mallGoods.get("isSeckill").toString())){
                        this.getKillThings(mallGoods);
                    }
                }
            }
        }
        return result;
    }

    public void getKillThings(Map mallGoods){
        try {
            Map<String, Object> seckillMap;
            String seckillMapStr = stringRedisTemplate.opsForValue().get("goodsSeckill:" + mallGoods.get("goodsId").toString());
            if (StringUtils.isEmpty(seckillMapStr)) {
                seckillMap =  mallDao.getSeckillByGoodsId(mallGoods.get("goodsId").toString());
                stringRedisTemplate.opsForValue().set("goodsSeckill:"  + mallGoods.get("goodsId").toString(), JSON.toJSONString(seckillMap, SerializerFeature.WriteMapNullValue),15, TimeUnit.SECONDS);
            }else {
                seckillMap = (Map<String, Object>) JSON.parse(seckillMapStr);
                SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                seckillMap.put("startTime",df2.format(new Date(Long.parseLong(seckillMap.get("startTime").toString()))));
                seckillMap.put("endTime",df2.format(new Date(Long.parseLong(seckillMap.get("endTime").toString()))));
            }
            if(seckillMap!=null && seckillMap.size()>0){
                String startTime = seckillMap.get("startTime").toString();
                String endTime = seckillMap.get("endTime").toString();
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date sd1=df.parse(startTime);
                Date sd2=df.parse(endTime);
                Date nowDate = new Date();
                mallGoods.put("seckillAllSecond",(sd2.getTime()-sd1.getTime())/1000);
                if(sd1.after(nowDate)){
                    //未开始
                    mallGoods.put("seckillStatus",0);
                    mallGoods.put("seckillSecond",(sd1.getTime()-nowDate.getTime())/1000);
                }else if(nowDate.after(sd2)){
                    //已结束
                    mallGoods.put("seckillStatus",2);
                    mallGoods.put("seckillSecond",(nowDate.getTime()-sd2.getTime())/1000);
                }else {
                    //进行中
                    mallGoods.put("seckillStatus",1);
                    mallGoods.put("seckillSecond",(sd2.getTime()-nowDate.getTime())/1000);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 商品分组-类目列表
     *
     * @param pid        pid
     * @param groupId    分组id
     * @param groupIsOrg 是否大b 1-是0-否
     * @param customerId 分组所属用户id(不传取request中信息)
     */
    @PostMapping("/listClassification")
    public List<Map<String, Object>> listClassification(@RequestBody Map<String, Object> param, HttpServletRequest request) {
        WxUser wxUser =  requestFilter.getWxUser(request);
        String orgId = wxUser.getOrgId();
        param.put("orgId", orgId);
        String customerId;
        if (!StringUtils.isEmpty(param.get("customerId"))) {
            customerId = param.get("customerId").toString();
        } else {
            customerId = wxUser.getCustomerId();
        }
        param.put("customerId", customerId);

        if(StringUtils.isEmpty(param.get("moduleId"))){
            param.put("showType", 2);
            param.put("moduleType", 3);
        }else{
            Map<String,Object> moduleInfo = classificationService.getModuleInfo(param);
            if(null == moduleInfo){
                throw GlobalException.build("参数错误");
            }
            // 1是自定义 2是分组
            Integer showType = Integer.valueOf(moduleInfo.get("showType").toString());
            if(2 == showType){
                param.put("groupId",moduleInfo.get("goodsGroupId"));
            }
            param.put("moduleType",moduleInfo.get("moduleType"));
            param.put("showType",showType);
        }
        return classificationService.listClassificationByGroupId(param);
    }

}
